package com.baijia.common.dto.request;

import com.baijia.services.ISignValidationService;
import com.baijia.util.ServiceLocator;

import com.google.common.collect.Maps;

import org.apache.commons.lang.StringUtils;

import java.lang.reflect.Field;
import java.util.TreeMap;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * 内部请求的抽象类
 * 
 * @title InternalRequest
 * @desc TODO
 * @author baiyue
 * @date 2017年1月4日
 * @version 1.0
 */
@Data
@Slf4j
public abstract class InternalRequest {

    private Integer sid; // 授权调用接口的用户类型
    private Long time; // 请求时间戳
    private String sign; // 签名

    protected boolean isValidRequest() {
        if (sid == null || time == null || StringUtils.isEmpty(sign)) {
            log.error("InternalRequest.isValidRequest : Parameter is invalid");
            return false;
        }

        TreeMap<String, Object> paramMap = Maps.newTreeMap();
        try {
            for (Field field : getClass().getFields()) {
                paramMap.put(field.getName(), field.get(this));
            }
        } catch (Exception e) {
            log.error("InternalRequest.isValidRequest : error when validating sign", e);
            return false;
        }

        if (paramMap.isEmpty()) {
            log.error("InternalRequest.isValidRequest : paramMap is empty");
            return false;
        }

        ISignValidationService validationService =
            ServiceLocator.getBean("signValidationServiceImpl", ISignValidationService.class);
        return validationService.validate(paramMap, sid, time, sign);
    }
}